package dao.impl;

import dao.BaseDao;
import dao.RentDao;
import entity.Rent;

import java.util.ArrayList;
import java.util.List;

public class RentDaoImpl extends BaseDao implements RentDao {
    @Override
    public List<Rent> findall() throws Exception{
        String sql="SELECT * FROM rent ORDER BY `status` ,maturityDate desc";
        return executeQuery(sql,rs->{
            List<Rent> rents=new ArrayList<>();
            try {
                while (rs.next()){
                    Rent rent=new Rent();
                    rent.setId(rs.getLong("id"));
                    rent.setUserName(rs.getString("userName"));
                    rent.setCarNum(rs.getString("carNum"));
                    rent.setStatus(rs.getInt("status"));
                    rent.setMaturityDate(rs.getDate("maturityDate"));
                    rents.add(rent);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return rents;
        });
    }

    @Override
    public Rent findbycarNum(String carNum) throws Exception{
        String sql="SELECT * FROM rent WHERE carNum=?";
        return executeQuery(sql,rs->{
            Rent rent=null;
            try {
                while (rs.next()){
                    rent=new Rent();
                    rent.setId(rs.getLong("id"));
                    rent.setUserName(rs.getString("userName"));
                    rent.setCarNum(rs.getString("carNum"));
                    rent.setStatus(rs.getInt("status"));
                    rent.setMaturityDate(rs.getDate("maturityDate"));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return rent;
        },carNum);
    }

    @Override
    public int add(Rent rent) throws Exception{
        String sql="INSERT INTO rent(userName,carNum,status,maturityDate) VALUES(?,?,?,?)";
        return executeUpdate(sql,rent.getUserName(),rent.getCarNum(),rent.getStatus(),rent.getMaturityDate());
    }

    @Override
    public int update(Rent rent) throws Exception{
        String sql="UPDATE rent SET status=? WHERE id=?";
        return executeUpdate(sql,rent.getStatus(),rent.getId());
    }
}
